<?php

namespace app\admin\controller\kuyou;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * bom工序
 *
 * @icon fa fa-circle-o
 */
class Procedure extends Backend
{

    /**
     * Procedure模型对象
     * @var \app\admin\model\kuyou\Procedure
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuyou\Procedure;
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set',$setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $list_k=>$list_v){
                $list[$list_k]['workshop_id'] = Db::name('kuyou_workshop')->where(['id'=>$list_v['workshop_id']])->value('name');
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('ids',$ids);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add($bom_id='')
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if(!isset($status)){
                    $this->error(__('Please fill in the detailed data'));
                }
                $number = 0;$all_money = 0;$data=[];
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)){//有产品编号
                        $number += (float)$params['number'][$k];
                        $all_money += (float)$params['all_money'][$k];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v])->field('id,goods_code,goods_name')->find();
                        $data[] = [
                            'bom_id'        =>  $params['bom_id'],
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $goods['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'unit_id'       =>  (float)$params['goods_unit'][$k],
                            'purchase'      =>  (float)$params['unit_price'][$k],
                            'number'        =>  (float)$params['number'][$k],
                            'money'         =>  (float)$params['all_money'][$k],
                            'default_unit'  =>  (float)$params['default_unit'][$k],
                            'basic_nmber'   =>  (float)$params['basic_nmber'][$k],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }
                if(empty($data)){
                    $this->error(__('Please fill in the detailed data'));
                }else{
                    $row = [
                        'bom_id'        =>  $params['bom_id'],
                        'purchase_code' =>  $params['purchase_code'],
                        'name'          =>  $params['name'],
                        'workshop_id'   =>  $params['workshop_id'],
                        'wages'         =>  $params['wages'],
                        'hours'         =>  $params['hours'],
                        'remark'        =>  $params['remark'],
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ];
                }

                $result = false;
                Db::startTrans();
                try {
                    if(!empty($row)){
                        $result = $this->model->insertGetId($row);
                    }

                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['procedure_id'] = $result;
                    }
                    Db::name('kuyou_bom_info')->insertAll($data);
                    $count = Db::name('kuyou_bom_info')->where(['bom_id'=>$params['bom_id']])->field('sum(number) as number,sum(money) as money')->select();
                    if(isset($count[0]['number'])){
                        Db::name('kuyou_bom')->where(['id'=>$params['bom_id']])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success(__('Added successfully'));
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $code = (new Goods())->getCodes('',30);
        $this->view->assign("code", $code);
        $this->view->assign("bom_id", $bom_id);
        $this->assignconfig('bom_id',$bom_id);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if(!isset($status)){
                    $this->error(__('Please fill in the detailed data'));
                }
                $number = 0;$all_money = 0;$data=[];
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)){//有产品编号
                        $number += (float)$params['number'][$k];
                        $all_money += (float)$params['all_money'][$k];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v])->field('id,goods_code,goods_name')->find();
                        $data[] = [
                            'bom_id'        =>  $params['bom_id'],
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $goods['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'unit_id'       =>  (float)$params['goods_unit'][$k],
                            'purchase'      =>  (float)$params['unit_price'][$k],
                            'number'        =>  (float)$params['number'][$k],
                            'money'         =>  (float)$params['all_money'][$k],
                            'default_unit'  =>  (float)$params['default_unit'][$k],
                            'basic_nmber'   =>  (float)$params['basic_nmber'][$k],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }
                if(empty($data)){
                    $this->error(__('Please fill in the detailed data'));
                }else{
                    $rowdata = [
                        'bom_id'        =>  $params['bom_id'],
                        'purchase_code' =>  $params['purchase_code'],
                        'name'          =>  $params['name'],
                        'workshop_id'   =>  $params['workshop_id'],
                        'wages'         =>  $params['wages'],
                        'hours'         =>  $params['hours'],
                        'remark'        =>  $params['remark'],
                        'updatetime'    => time(),
                    ];
                }

                $result = false;
                Db::startTrans();
                try {
                    if(!empty($rowdata)){
                        $result = $this->model->where(['id'=>$row['id']])->update($rowdata);
                    }

                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['procedure_id'] = $row['id'];
                    }
                    Db::name('kuyou_bom_info')->where(['procedure_id'=>$row['id']])->delete();
                    Db::name('kuyou_bom_info')->insertAll($data);
                    $count = Db::name('kuyou_bom_info')->where(['bom_id'=>$params['bom_id']])->field('sum(number) as number,sum(money) as money')->select();
                    if(isset($count[0]['number'])){
                        Db::name('kuyou_bom')->where(['id'=>$params['bom_id']])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success(__('Edited successfully'));
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $purchase_info = Db::name('kuyou_bom_info')->where(['procedure_id'=>$row['id']])->select();
        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
            $purchase_info[$purchase_info_k]['unit'] = json_decode((new GoodsPurchase())->getUnit($purchase_info_v['goods_code']),true);
        }
        $this->view->assign("purchase_info", $purchase_info);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    Db::name('kuyou_bom_info')->where(['procedure_id'=>$v['id']])->delete();

                    $count = Db::name('kuyou_bom_info')->where(['bom_id'=>$v['bom_id']])->field('sum(number) as number,sum(money) as money')->select();
                    Db::name('kuyou_bom')->where(['id'=>$v['bom_id']])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
